<template>
  <view class="evaluation">
    <!-- detail.orderItemList -->
    <block v-for="(item, index) in detail.orderItemList" :key="index">
      <view class="evaluation__goods">
        <goods :goodsData="item"></goods>
      </view>
      <view class="evaluation__textarea">
        <u--textarea @focus="editIndex=index" @input="areaChange" border="true" :autoHeight="true" height="100" placeholder="已经使用一段时间了，有更多宝贝心得？分享给买得他们吧" ></u--textarea>
      </view>
      <!-- <view class="evaluation__images">
        <view class="image--add" @click="handleTakePhoto" data-key="pictures" :data-index="index">
          <image src="http://medusa-small-file.oss-cn-hangzhou.aliyuncs.com/images/icon-c.png"></image>
          添加图片
        </view>
        <view v-for="(item, imageIndex) in form.productEvaluateDtoList[index].pictures" :key="imageIndex"
          class="image--item">
          <view class="del" @click="handleDelPhoto" data-key="pictures" :data-index="index" :data-imageIndex="imageIndex">
            <i class="iconfont icontijiaodingdan-youhuiquan-guanbi"></i>
          </view>
          <image :src="item" @click="handleSeePhoto" :data-item="item"></image>
        </view>
      </view> -->
      <view style="background:#fff">
        <u-upload
        :fileList="form.productEvaluateDtoList[index].pictures"
        @afterRead="afterRead"
        @delete="deletePic"
        :name="index"
        multiple
        :maxCount="5"
        width="110"
        height="110"
        >
        <view class="evaluation__images">
          <view class="image--add" data-key="pictures">
            <image src="http://medusa-small-file.oss-cn-hangzhou.aliyuncs.com/images/icon-c.png"></image>
            添加图片
          </view>
        </view>
        </u-upload>
      </view>
      <view>
        <u-cell-group :customStyle="{background:'#fff'}">
          <u-cell title="综合评分" value="满意请给5分哦" :border="false"></u-cell>
           <u-cell title="商品质量">
             <u-rate slot="title" v-model="form.productEvaluateDtoList[index].rate"></u-rate>
           </u-cell>
        </u-cell-group>
      </view>
    </block>
    <div class="evaluation__button" @click="submit">提交评论</div>
  </view>
</template>

<script lang='ts'>
  import {
    Component,
    Vue
  } from 'vue-property-decorator'
  import {
    evaluate,
    getOrderDetail
  } from "@/api/modules/order";
  import {
    uploadFile
  } from "@/utils/upload";
  // import {
  //   isArray
  // } from 'lodash';

  @Component({})
  export default class OrderEvaluation extends Vue {
    message: string = ""
    detail: any = {}
    // 评价表单
    form: any = {
      orderId: "",
      productEvaluateDtoList: [] as Array < {
        comment: string;
        picture: string;
        // 本地维护的图片数组
        pictures: string[];
        // 原始图片
        originPhotos: string[];
        productSkuId: string;
        rate: number;
      } > ,
      shopRate:5
    }
    editIndex=0
    // 是否已提交
    submitted: boolean = false
    get appMode() {
      return this.$store.state.settingStore.shopSetting.appMode
    }
    // 页面周期函数--监听页面加载
    onLoad({
      id = "1324995623470723073"
    }) {
      this.getOrderDetail(id);
      this.$Pubsub.on("app-launch", () => {
        this.getOrderDetail(id);
      });
    }
    async afterRead(event){
      let lists = [].concat(event.file)
				let fileListLen = this.form.productEvaluateDtoList[event.name].pictures.length
				lists.map((item) => {
				this.form.productEvaluateDtoList[event.name].pictures.push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result =await uploadFile(lists[i].thumb)
					let item = this.form.productEvaluateDtoList[event.name].pictures[fileListLen]
					this.form.productEvaluateDtoList[event.name].pictures.splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))
					fileListLen++
				}
    }
    deletePic(event) {
				this.form.productEvaluateDtoList[event.name].pictures.splice(event.index, 1)
		}
    getOrderDetail(id) {
      getOrderDetail(id)
        .then(detail => {
          const orderItemList = detail.orderItemList.filter(item=>{
            return !item.afs || item.afs.status==="CLOSE"
          })
          this.setData({
            detail:{...detail,orderItemList},
            "form.productEvaluateDtoList": this.setProductEvaluateDtoList(
              orderItemList,
            ),
          });
        })
        .catch(err => {
          this.$Popup.toast(err || "详情获取失败");
        });
    }

    /** 设置评分队列 */
    setProductEvaluateDtoList(list) {
      return list.map(item => {
        return {
          comment: "",
          picture: "",
          // 本地维护的图片数组
          pictures: [],
          productSkuId: item.productSkuId,
          rate: 0,
        };
      });
    }
    areaChange(e){
      this.form.productEvaluateDtoList[this.editIndex].comment=e
    }
    /** 监听表单输入并设置对应值 */
    //rateChange(e) {
      // console.log(e)
      // console.log(this.rateValue)
      // console.log(this.editIndex)
      // this.form.productEvaluateDtoList[this.editIndex].rate = e
    //}

    /** 删除 */
    // handleDelPhoto({
    //   currentTarget: {
    //     dataset: {
    //       index,
    //       key,
    //       imageIndex
    //     },
    //   },
    // }) {
    //   const pictures = this.form.productEvaluateDtoList[index].pictures;
    //   pictures.splice(imageIndex, 1);
    //   this.setData({
    //     [`form.productEvaluateDtoList[${index}].${key}`]: pictures,
    //   });
    // }

    // handleSeePhoto({
    //   currentTarget: {
    //     dataset: {
    //       item
    //     },
    //   },
    // }) {
    //   uni.previewImage({
    //     current: item,
    //     urls: [item]
    //   });
    // }

    /** 拍照 */
    // handleTakePhoto({
    //   currentTarget: {
    //     dataset: {
    //       index
    //     },
    //   },
    // }) {
    //   const pictures = this.form.productEvaluateDtoList[index].pictures;
    //   if (pictures.length >= 5) {
    //     return uni.showToast({
    //       title: "已达到上传上限",
    //       icon: "none"
    //     });
    //   }
    //   uni.chooseImage({
    //     count: 5,
    //     sizeType: ["original", "compressed"],
    //     sourceType: ["camera"],
    //     success: async ({
    //       tempFilePaths
    //     }) => {
    //       console.log('tempFilePaths',tempFilePaths)
    //       if (isArray(tempFilePaths)) {
    //         tempFilePaths.forEach(url => {
    //           uploadFile(url)
    //             .then(res => {
    //               this.form.productEvaluateDtoList[index].pictures.push(res)
    //             })
    //             .catch(err => {
    //               uni.showToast({
    //                 title: err || "上传失败",
    //                 icon: "none"
    //               });
    //             });
    //         })
    //       }
    //     },
    //     fail: err => {
    //       uni.showToast({
    //         title: err || "详情获取失败",
    //         icon: "none"
    //       });
    //     }
    //   })

    // }

    /** 将图片转为字符串 */
    tranfromPics() {
      const productEvaluateDtoList = this.form.productEvaluateDtoList.map(
        item => {
          item.picture = item.pictures.map(ite=>{
            return ite.url
          }).join(",");
          return item;
        },
      );
      this.setData({
        "form.productEvaluateDtoList": productEvaluateDtoList,
      });
    }

    /**
     * 验证表单
     */
    verification() {
      const {
        productEvaluateDtoList
      } = this.form;
      const evLen = productEvaluateDtoList.every(item => {
        return item.rate >= 1
      });
      if (!evLen) {
        this.$Popup.toast("商品评分不可为空");
        return false;
      }
      return true;
    }

    /** 提交评价 */
    submit() {
      if (!this.verification() || this.submitted) return;

      this.setData({
        submitted: true
      });
      this.tranfromPics();
      
      evaluate(
          Object.assign({}, this.form, {
            orderId: this.detail.id
          }),
        )
        .then(() => {
          uni.showToast({
            title: "评价成功",
            icon: "success"
          });
          setTimeout(() => {
            uni.redirectTo({
              url: "/subcontract/pages/order/order?type=4"
            });
          }, 1500);
        })
        .catch(err => {
          this.setData({
            submitted: false
          });
          uni.showToast({
            title: err || "详情获取失败",
            icon: "none"
          });
        });
    }
  }
</script>

<style lang="scss" scoped>
  @import "@/assets/styles/var";

  .evaluation {
    background: $main-background;
    min-height: 100vh;
    padding-bottom: 100px;

    @mixin p($v: 10px, $l: 10px) {
      padding: 10px 10px;
    }

    &__images {
      @include flex(flex-start);
      @include p;

      width: 100%;
      background: #fff;
      flex-wrap: wrap;

      view:nth-child(4n) {
        margin-right: 0;
      }

      .image--add {
        @include flex;

        flex-direction: column;
        width: 80px;
        height: 80px;
        border: 1px dashed $main-border-color;
        font-size: 12px;
        color: #ccc;
        margin-right: 10px;
        margin-bottom: 10px;

        image {
          width: 20px;
          height: 20px;
        }
      }

      .image--item {
        width: 80px;
        height: 80px;
        margin-right: 10px;
        margin-bottom: 10px;
        position: relative;

        .del {
          $s: 15px;
          width: $s;
          height: $s;
          // background: rgba($color: #000000, $alpha: .8);
          position: absolute;
          right: -$s/2;
          top: -$s/2;
          border-radius: 50%;
        }

        image {
          width: 100%;
          height: 100%;
        }
      }
    }

    &__textarea {
      min-height: 100px;
      background: #fff;

      .van-field__body--textarea {
        min-height: 48px;
      }

      .van-field__input {
        padding-top: 10px;
        min-height: 240rpx !important;
      }
    }

    &__goods {
      padding: 10px 10px;
      border-bottom: 1px solid $main-border-color;
      background: #fff;
    }

    &__rate {
      margin-bottom: 10px;
      // @include flex();
      position: relative;
      font-size: 30rpx;
      background:white
    }

    &__button {
      box-sizing: border-box;
      position: fixed;
      bottom: 0;
      left: 0;
      width: 100%;
      padding: 10px 15px;
      text-align: center;
      background: $main-light-color;
      color: #fff;
      z-index: 99;
    }
  }
</style>